package task

import (
	"errors"
	"k8s-admin/global"
	"k8s-admin/models"
	"k8s-admin/utils"
)

type InterfaceTimer interface {
	Create(req *models.TimerReq) error
	List() (*models.TimerRes, error)
	StartTimer(timerNummber string) (*models.Timing, error)
	// HistoryLists() (*models.TaskRes, error)
	// Delete(TaskNumber string) error
	// Update(TasksNumber string, req *models.TaskReq) error
}

type TimersInfo struct {
}

func NewInterfaceTimers() InterfaceTimer {
	return &TimersInfo{}
}
func (d *TimersInfo) Create(req *models.TimerReq) error {
	timer_number := utils.GemSnowFlask(req.Title)
	err := global.GORM.Create(&models.Timing{
		Title:       req.Title,
		TimerNumber: timer_number,
		ShellExec:   req.ShellExec,
		Remark:      req.Remark,
		AlarmID:     req.AlarmID,
		HostIP:      req.HostIP,
		CronID:      req.CronID,
		PeriodTime:  req.PeriodTime,
	}).Error
	if err != nil {
		return err
	} else {
		return nil
	}
}

func (d *TimersInfo) List() (*models.TimerRes, error) {
	timerLists := []models.Timing{}
	tx := global.GORM.Find(&timerLists)
	if tx.Error != nil {
		return nil, tx.Error
	} else if tx.RowsAffected == 0 {
		return nil, errors.New("更新失败，没有该数据")
	} else {
		return &models.TimerRes{Items: timerLists, Total: len(timerLists)}, nil
	}
}

func (d *TimersInfo) StartTimer(timerNummber string) (*models.Timing, error) {
	timer := models.Timing{}
	err := global.GORM.Where("timer_number=?", timerNummber).First(&timer).Error
	if err != nil {
		return nil, err
	} else {
		return &timer, nil
	}
}
